<?php
/**
 * Created by: i@fedax.cn
 * Date: 2018/7/29 0:16
 * user:帅帅吴
 */

namespace app\admin\model;


class FamilyRoom extends DataBase
{
    protected $autoWriteTimestamp = true;

    protected $roomType = [1=>'绿色推荐',2=>'家族流水',3=>'家族牌照陪玩',4=>'家族无牌照流水'];

    public function getDataList()
    {
        $page_config = array(
            'page' => input('get.offset', 1),
            'limit' => input('get.limit', 10)
        );
        $order = input('sort', 'ss_family_room.id') . ' ' . input('order', 'desc');
        $where = []; //查询条件
        if (!empty(input('start_time')) && !empty(input('end_time'))) {
            $start = strtotime(input('start_time'));
            $end = strtotime(input('end_time'));
            $where[] = ['ss_family_room.create_time', 'between', [$start, $end]];
        }
        if (!empty(input('value')) && !empty(input('key'))) {
            $value = input('value');
            $key = input('key');
            if ($key == 'r_uid') {
                $r_id = User::where('u_id','=',$value)->value('id');
                $where[] = ['ss_rooms.r_id', '=',$r_id];
            }
            if ($key == 'f_uid') {
                $user_id = User::where('u_id','=',$value)->value('id');
                $where[] = ['ss_family.user_id','=', $user_id];
            }
        }
        $data = $this
            ->view('ss_family_room', 'id,room_id,type,label,alipay_card,alipay_name,scale,check_exchange,create_time')
            ->view('ss_family', 'f_name,user_id', 'ss_family_room.family_id = ss_family.id')
            ->view('ss_rooms', 'r_name,r_id', 'ss_family_room.room_id = ss_rooms.id')
            ->where($where)
            ->order($order)
            ->paginate($page_config);
        foreach ($data as $key => $value){
            $data[$key]['r_head'] = User::where('id', $value['r_id'])->value('u_id');
            $data[$key]['f_head'] = User::where('id', $value['user_id'])->value('u_id');
        }
        return $data;
    }

    public function flowFamilyInfoData()
    {
        $roomId = input('get.roomId');
        $queryTime = input('get.queryTime');
        if (!empty($roomId) && $queryTime != date('Y-m')) {
            if (strtotime($queryTime) > time()) {
                return ['resultCode' => 110, 'resultData' => null, 'resultDes' => '查询结果为空!'];
            } else {
                $startTime = strtotime($queryTime . '-01');
                $endTime = strtotime(date('Y-m-d', strtotime("$queryTime + 1 month -1 day")) . ' 23:59:59');
            }
        } else {
            $startTime = strtotime(date('Y-m') . '-01');
            $endTime = time();
        }
        $dayNum = ceil(($endTime - $startTime) / (3600 * 24));
        $data = [];
        for ($i = 0; $i < $dayNum; $i++) {
            $arr['date'] = date('Y-m-d', $startTime + 3600 * 24 * $i);
            $arr['diamonds'] = GiftRecord::where([['room_id', '=', $roomId], ['create_time', 'between', [strtotime($arr['date']), strtotime($arr['date'] . ' 23:59:59')]]])->sum('gift_price');
            $data[] = $arr;
        }
        return ['resultCode' => 100, 'resultData' => $data, 'resultDes' => '查询成功!'];
    }

    public function flowFamilyGiftInfo()
    {
        return GiftRecord::where([['room_id', '=', input('get.roomId')], ['create_time', 'between', [strtotime(input('get.dates')), strtotime(input('get.dates') . ' 23:59:59')]]])
            ->field('send_user_id,receive_user_id,gift_type,gift_price,num,create_time')->select();
    }

    public function flowFamilyHourInfo()
    {
        $times = strtotime(input('get.dates'));
        $data = [];
        for ($i = 0; $i < 24; $i++) {
            $arr['hours'] = $i . ':00~' . ($i + 1) . ':00';
            $arr['diamonds'] = GiftRecord::where([['room_id', '=', input('get.roomId')], ['create_time', 'between', [$times + $i * 3600, $times + ($i + 1) * 3600]]])->sum('gift_price');
            $data[] = $arr;
        }
        return $data;
    }

    /**
     * @return array
     * @user shuai wu
     * @date 2018/12/29
     * @title 删除家族房间
     */
    public function flowFamilyRoomDel()
    {
        $id = input('get.id');
        $re = $this->where('id','=',$id)->delete();
        if($re) return ['code'=>100,'msg'=>'删除成功'];
        else return ['code'=>-100,'msg'=>'删除失败'];
    }

    /**
     * @return array
     * @user 帅帅吴
     * @date 2018/12/30
     * @title 家族房间添加
     */
    public function flowFamilyAdd()
    {
        $newData = input('post.');

        $user_id = User::where('u_id','=',$newData['u_id'])->value('id');
        if(!$user_id) return ['code'=>-100,'msg'=>'没找到该ID'];

        $room_id = Room::where('r_id','=',$user_id)->value('id');
        if(!$room_id) return ['code'=>-100,'msg'=>'没找到该房间'];

        $re = $this->where('room_id','=',$room_id)->find();
        if($re) return ['code'=>-100,'msg'=>'该房间已使用'];

        $newData['room_id'] = $room_id;
        $res = $this->save($newData);

        if($res) return ['code'=>100,'msg'=>'添加成功'];
        else return ['code'=>-100,'msg'=>'添加失败'];

    }

    /**
     * @return array
     * @user 帅帅吴
     * @date 2018/12/30
     * @title 家族房间修改
     */
    public function flowFamilyEdit()
    {
        $newData = input('get.');
        $res = $this->save($newData,['id'=>$newData['id']]);
        if($res) return ['code'=>100,'msg'=>'修改成功'];
        else return ['code'=>-100,'msg'=>'修改失败'];
    }
    /**
     * Notes: 家族房间流水信息
     * User: 王俊成
     * Date: 2018/11/6
     * Time: 15:01
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function familyRoomFlowingData(){
        $pageConfig = [
            'page' => input('get.pageNum',1),
            'list_rows' => input('get.limit',10)
        ];

        $map = true;
        $keyWords = input('get.keyWords');

        if(!empty($keyWords) || $keyWords == '0'){
            $key = input('get.key');

            if($key == 'f_uid'){

                $user_id = User::where('u_id','=',$keyWords)->value('id');
                $family_id = Family::where('user_id','=',$user_id)->value(' id');
                $map[] = ['family_id','=',$family_id];
                //  halt($map);
            }
            if($key == 'r_uid'){

                $user_id = User::where('u_id','=',$keyWords)->value('id');
                $room_id = Room::where('r_id','=',$user_id)->value(' id');
                $map[] = ['room_id','=',$room_id];
                // halt($map);
            }

            if($key == 'f_name'){

                $family_id = Family::where($key,'=',$keyWords)->value('id');
                $map[] = ['family_id','=',$family_id];
                // halt($map);
            }

            if($key == 'r_name'){

                $room_id = Room::where($key,'=',$keyWords)->value('id');
                $map[] = ['room_id','=',$room_id];
                //  halt($map);
            }
        }
        //此处暂时用了连表处理，连表数过多，如果有性能问题，请更换方式
//        $data = $this->alias('a')->fieldRaw('a.id,a.family_id,a.room_id,a.type,a.label,a.alipay_card,a.alipay_name,a.scale,b.user_id,b.f_name,c.r_id,c.r_name,SUM(d.gift_price) as flowing_num,e.u_id')
//            ->leftJoin('family b','a.family_id=b.id')->leftJoin('rooms c','a.room_id=c.id')
//            ->leftJoin('gift_record d','a.room_id=d.room_id')->leftJoin('users e','b.user_id=e.id')
//            ->where($map)->group('d.room_id')->order('flowing_num DESC')->paginate($pageConfig);
//        if($data){
//            foreach($data as $key => $value){
//               $value['room_uid'] = get_uid($value['r_id']);
//               $value['scale'] = $value['scale'].'%';
//               $data[$key] = $value;
//            }
//        }

        $data = $this->where($map)->paginate($pageConfig);

        foreach($data as $key => $value){

            $familyInfo = Family::where('id','eq',$value['family_id'] )->field('f_name,user_id')->find();

            $u_id = User::where('id','=',$familyInfo['user_id'])->value('u_id');

            $data[$key]['f_name'] = $familyInfo['f_name'];
            $data[$key]['u_id'] = $u_id;

            $roomInfo = Room::where('id','=',$value['room_id'])->field('r_id,r_name')->find();
            $r_id = User::where('id','=',$roomInfo['r_id'])->value('u_id');

            $data[$key]['r_name'] = $roomInfo['r_name'];
            $data[$key]['room_uid'] =$r_id;

        }
       // halt($data);
        return $data;
    }

    /**
     * Notes: 家族房间上周流水导出
     * User: 王俊成
     * Date: 2018/11/6
     * Time: 16:01
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function familyRoomFlowingExport(){
        $startTime = strtotime(date('Y-m-d',strtotime('last week')));
        $endTime = $startTime + 7 * 24 * 3600;
        //获取数据
        $data = $this->alias('a')->field('family_id,room_id,a.type,label,alipay_card,alipay_name,scale,a.create_time,f_name,user_id')
            ->leftJoin('family b','a.family_id=b.id')->where([['b.status','=',1],['b.type','=',1]])->select()->toArray();
        if($data){
            foreach($data as $key => $value){
                $value['room_name'] = get_room_name($value['room_id']);
                $value['room_uid'] = get_uid(Room::where('id',$value['room_id'])->value('r_id'));
                $value['last_week_flowing'] = GiftRecord::where([['room_id','=',$value['room_id']],['create_time','between',[$startTime,$endTime]]])
                    ->sum('gift_price');
                $value['type'] = $this->roomType[$value['type']];
                if($value['last_week_flowing'] > 0){
                    $value['scale'] = $value['scale'].'%';
                    $value['money'] = $value['last_week_flowing'] * 0.1 * $value['scale']/100;
                    $value['whole_money'] = round($value['last_week_flowing'] * 0.1 * $value['scale']/100);
                    for($i = 0;$i < 7;$i++){
                        $dates = date('Y-m-d',$startTime + $i * 24 * 3600);
                        $value[$dates] = GiftRecord::where([['room_id','=',$value['room_id']],['create_time','between',[strtotime($dates),strtotime($dates.' 23:59:59')]]])
                            ->sum('gift_price');
                    }
                    $data[$key] = $value;
                }
                else
                    unset($data[$key]);
            }
            $data = array_merge($data);
        }
        $fileName = '家族房间流水';
        $remarkData = ['家族房间流水'];
        $cellTitle = [
            ['f_name','家族名'],
            ['room_name','房间名'],
            ['room_uid','房主ID'],
            ['type','房间属性'],
            ['alipay_name','支付宝姓名'],
            ['alipay_card','支付宝账号'],
            ['scale','返现比例'],
            ['last_week_flowing','上周流水'],
            ['money','金钱'],
            ['whole_money','金钱(取整)'],
            ['create_time','创建时间']
        ];
        for($i = 0;$i < 7;$i++){
            $dates = date('Y-m-d',$startTime + $i * 24 * 3600);
            $cellTitle[] = [$dates,$dates];
        }
        $excelObj = new \app\common\api\Excel();
        $excelObj->exportExcel($fileName,$remarkData,$cellTitle,$data);
    }
}